package org.hxzon.demo.juntai.csserver.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import org.hxzon.demo.juntai.csserver.common.Config;
import org.hxzon.demo.juntai.csserver.server.Util;

public class Client {

    private int serverPort;
    ByteBuffer bufSend = ByteBuffer.allocate(Config.maxByteBuffer);

    public Client(int port) {
        this.serverPort = port;
    }

    public void connect() {
        try {
            //Selector selector = Selector.open();
            //open and connect
            SocketChannel sc = SocketChannel.open(new InetSocketAddress(serverPort));
            sc.configureBlocking(false);
            //sc.register(selector, SelectionKey.OP_CONNECT);
            while (!sc.finishConnect()) {

            }
            while (true) {
                //
                BufferedReader inConsole = new BufferedReader(new InputStreamReader(System.in, Config.encoding));//
                String strConsole = inConsole.readLine();
                bufSend.clear();
                if ("bye".equals(strConsole)) {
                    sc.close();
                } else if ("test long".equals(strConsole)) {
                    int c = '1';
                    byte[] bytes = new byte[1024 * 500];
                    for (int i = 0; i < bytes.length; i++) {
//                        c = c + (i / 1000);
//                        if (c >= '~') {
//                            c = '1';
//                        }
                        bytes[i] = (byte) (c);
                    }
                    bytes[bytes.length - 1] = '~';
                    bufSend.putInt(bytes.length);
                    bufSend.put(bytes);
                    bufSend.flip();
                    int countTotalWrite = 0;
                    while (bufSend.hasRemaining()) {
                        int countWrite = sc.write(bufSend);
                        countTotalWrite += countWrite;
                    }
                    Util.debug("countTotalWrite:" + countTotalWrite);
                } else {
                    byte[] bytes = strConsole.getBytes(Config.encoding);
                    bufSend.putInt(bytes.length);
                    bufSend.put(bytes);
                    bufSend.flip();//for write
                    int countTotalWrite = 0;
                    while (bufSend.hasRemaining()) {
                        int countWrite = sc.write(bufSend);
                        countTotalWrite += countWrite;
                    }
                    Util.debug("countTotalWrite:" + countTotalWrite);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String args[]) {
        Client client = new Client(Config.port);
        client.connect();
    }
}
